package com.example.fangyimanagement;

import com.example.fangyimanagement.core.LoginUser;
import com.example.fangyimanagement.core.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/hsjcdManage")
public class hsjcdManageController {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 创建一个核酸检测点
     * @param param
     * @return
     */
    @RequestMapping("/addHsjcd")
    public Result<Void> addHsjcd(@RequestBody Map<String, String> param) {
        String hsjcdName = param.get("name");
        String districtCode = param.get("districtCode");
        String manager = param.get("manager");
        String addressDetail = param.get("addressDetail");
        String openTime = param.get("openTime");
        String closeTime = param.get("closeTime");
        String status = param.get("status");
        String windowNum = param.get("windowNum");
        //        操作数据库
        String sql = "insert into hsjcd_data (name, district_code, manager_account,address_detail,morning_open_time,evening_close_time,status, window_num) " +
                "values (?, ?, ?, ?, ?, ?, ?, ?)";
        int rows = this.jdbcTemplate.update(sql, hsjcdName, districtCode, manager, addressDetail, openTime, closeTime, status, windowNum);
        if (rows > 0) {
            return Result.success();
        } else {
            return Result.failed("添加失败");
        }
    }

    /**
     * 删除一个核酸检测点
     * @param param
     * @return
     */
    @RequestMapping("/deleteHsjcd")
    public Result<Void> deleteHsjcd(@RequestBody Map<String, String> param) {
        String id = param.get("id");
        /**
         * 操作数据库
         */
        int rows = this.jdbcTemplate.update("delete from hsjcd_data where id =?", id);
        if (rows > 0) {
            return Result.success();
        } else {
            return Result.failed("删除失败");
        }
    }

    /**
     * 修改核酸检测点的信息
     * @param param
     * @return
     */
    @RequestMapping("/updateHsjcd")
    public Result<Void> updateHsjcd(@RequestBody Map<String, String> param) {
        String id = param.get("id");
        String hsjcdName = param.get("name");
        String districtCode = param.get("districtCode");
        String manager = param.get("manager");
        String addressDetail = param.get("addressDetail");
        String openTime = param.get("openTime");
        String closeTime = param.get("closeTime");
        String status = param.get("status");
        String windowNum = param.get("windowNum");
        //        操作数据库
        String sql = "update hsjcd_data set name=?, district_code=?, manager_account=?, address_detail=?, morning_open_time=?, " +
                "evening_close_time=?, status=?, window_num=? where id =?";
        int rows = this.jdbcTemplate.update(sql, hsjcdName, districtCode, manager, addressDetail, openTime, closeTime, status, windowNum, id);
        if (rows > 0) {
            return Result.success();
        } else {
            return Result.failed("编辑失败");
        }
    }

    /**
     * 核酸检测点列表查询
     * @param param
     * @param loginUser
     * @return
     */
    @RequestMapping("/hsjcdList")
    public Result<List<Map<String, Object>>> hsjcdList(@RequestBody Map<String, String> param, LoginUser loginUser) {
        String account = loginUser.getAccount();
        List<Map<String, Object>> accountRoleOrgList = this.jdbcTemplate.queryForList("SELECT name, role_code, org_code FROM glpt_user WHERE account=?", account);
        /**
         * 根据登录人账号找到了角色和组织编码，查数据时就要做权限控制
         */
        if (accountRoleOrgList.size() > 0) {
            String accountRole = (String) accountRoleOrgList.get(0).get("role_code");
            String accountOrg = (String) accountRoleOrgList.get(0).get("org_code");
            int page = Integer.parseInt(param.get("page"));
            int size = Integer.parseInt(param.get("size"));
            String manager = param.get("manager");
            String name = param.get("name");
            String districtCode = param.get("districtCode");
            String sql = "SELECT hsjcd_data.id AS id, hsjcd_data.name, " +
                    "hsjcd_data.district_code AS districtCode, glpt_org.org_name AS districtName, " +
                    "hsjcd_data.manager_account, glpt_user.name AS managerName, " +
                    "address_detail AS addressDetail, longitude, latitude, " +
                    "morning_open_time AS openTime, evening_close_time AS closeTime, window_num AS windowNum, status FROM hsjcd_data " +
                    "JOIN glpt_user ON hsjcd_data.manager_account = glpt_user.account " +
                    "JOIN glpt_org ON hsjcd_data.district_code = glpt_org.org_code WHERE 1=1 ";
            List<Object> paramList = new ArrayList<>();
            if (manager != null && !manager.isEmpty()) {
                sql = sql + " AND hsjcd_data.manager_account = ?";
                paramList.add(manager);
            }
            if (name != null && !name.isEmpty()) {
                sql = sql + " AND hsjcd_data.name = ?";
                paramList.add(name);
            }
            if (districtCode != null && !districtCode.isEmpty()) {
                sql = sql + " AND hsjcd_data.district_code = ?";
                paramList.add(districtCode);
            }
            /**
             * 如果是区级管理员，就要只查本区的范围
             * 如果是核酸检测点管理员，只要查自己名下的
             */
            if (accountRole.equals("district_manager") && accountOrg != null) {
                sql = sql + " AND hsjcd_data.district_code = ?";
                paramList.add(accountOrg);
            } else if (accountRole.equals("hsjcdManager")) {
                sql = sql + " AND hsjcd_data.manager_account = ?";
                paramList.add(account);
            }
            String countSql = "SELECT COUNT(1) FROM ("+ sql +") t";
            Integer count = this.jdbcTemplate.queryForObject(countSql, Integer.class, paramList.toArray());

            String querySql = sql + " ORDER BY hsjcd_data.id LIMIT ?, ?";
            paramList.add((page - 1) * size);
            paramList.add(size);
            List<Map<String, Object>> hsjcdList = this.jdbcTemplate.queryForList(querySql, paramList.toArray());

            return Result.success(hsjcdList).setTotal(count);
        } else {
            return Result.failed("查询失败，请稍后再试");
        }
    }

    /**
     * 移动端用户获取所有核酸检测点
     * @param param
     * @param loginUser
     * @return
     */
    @RequestMapping("/allHsjcdList")
    public Result<List<Map<String, Object>>> allHsjcdList(@RequestBody Map<String, String> param, LoginUser loginUser) {
        List<Map<String, Object>> hsjcdList = this.jdbcTemplate.queryForList("SELECT * from hsjcd_data");
        return Result.success(hsjcdList);
    }
    /**
     * 我管理的核酸检测点
     * @param param
     * @param loginUser
     * @return
     */
    @RequestMapping("/myHsjcdList")
    public Result<List<Map<String, Object>>> myHsjcdList(@RequestBody Map<String, String> param, LoginUser loginUser) {
        String manager = loginUser.getAccount();
        String sql = "SELECT hsjcd_data.id AS id, hsjcd_data.name, " +
                "hsjcd_data.district_code AS districtCode, glpt_org.org_name AS districtName, " +
                "hsjcd_data.manager_account, glpt_user.name AS managerName, " +
                "address_detail AS addressDetail, longitude, latitude, " +
                "morning_open_time AS openTime, evening_close_time AS closeTime, window_num AS windowNum, status FROM hsjcd_data " +
                "JOIN glpt_user ON hsjcd_data.manager_account = glpt_user.account " +
                "JOIN glpt_org ON hsjcd_data.district_code = glpt_org.org_code WHERE 1=1 ";
        List<Object> paramList = new ArrayList<>();
        if (manager != null && !manager.isEmpty()) {
            sql = sql + " AND hsjcd_data.manager_account = ?";
            paramList.add(manager);
        }
        sql = sql + " ORDER BY hsjcd_data.id";
        List<Map<String, Object>> hsjcdList = this.jdbcTemplate.queryForList(sql, paramList.toArray());
        return Result.success(hsjcdList);
    }

    /**
     * 所有核酸检测点的负责人列表
     * @param param
     * @return
     */
    @RequestMapping("/getManagerList")
    public Result<List<Map<String, Object>>> getManagerList(@RequestBody Map<String, String> param, LoginUser loginUser) {
        String account = loginUser.getAccount();
        List<Map<String, Object>> accountRoleOrgList = this.jdbcTemplate.queryForList("SELECT name, role_code, org_code FROM glpt_user WHERE account=?", account);
        /**
         * 根据登录人账号找到了角色和组织编码，查数据时就要做权限控制
         */
        if (accountRoleOrgList.size() > 0) {
            String accountRole = (String) accountRoleOrgList.get(0).get("role_code");
            String accountOrg = (String) accountRoleOrgList.get(0).get("org_code");
            String sql = "SELECT name, account AS code FROM glpt_user WHERE role_code = 'hsjcdManager'";
            List<Object> paramList = new ArrayList<>();
            /**
             * 区级管理员可以查本区所有核酸点管理员
             * 核酸点管理员就只能查到自己
             */
            if (accountRole.equals("district_manager") && accountOrg != null) {
                sql = sql + " AND org_code = ?";
                paramList.add(accountOrg);
            } else if (accountRole.equals("hsjcdManager") && accountOrg != null) {
                sql = sql + " AND org_code = ? AND account = ?";
                paramList.add(accountOrg);
                paramList.add(account);
            }
            List<Map<String, Object>> managerList = this.jdbcTemplate.queryForList(sql, paramList.toArray());
            return Result.success(managerList);
        } else {
            return Result.failed("查询失败，请稍后再试");
        }
    }
}
